import React, { useState, useEffect, useRef, useImperativeHandle } from "react";
import Canvas from "./components/Canvas";
import computedYYYYMMDDToHHssmm from "../utils/computedYYYYMMDDToHHssmm";
import "./index.less";
import { message } from "antd";
import moment from "moment";
import ToolTip from "./components/ToolTip";
import Modal from "./components/Modal";
import FormItem from "./components/FormItem";

let ajaxM3u8TimesFlag = 0;

const XBaseFn = (props: any = {}, ref: React.Ref<unknown> | undefined) => {
  const {
    apiParams = {},
    onAudioPlaying,
    onAudioJump,
    onAudioPlayOrPause,
    onClickPlayBtn,
    onAudioPlaybackRateChange,
    onAudioVolumeChange,
    onAudioTimeLineClick = () => {},
    onAudioJumpButtonClick,
    onReady = () => {},
    onClickRecord,
    markListWidth,
    apiPrefixUri,
    apiMapping,
  } = props;
  const { orderId, productId, district, ...rest } = apiParams;

  const sliderWrapperRef = useRef<HTMLDivElement>(null!);
  const cRef = useRef<any>();
  const [images, setImages] = useState<Array<string>>(['https://tse2-mm.cn.bing.net/th/id/OIP-C.Sl0CKQQpBxWoOub28c2N-wAAAA?pid=ImgDet&rs=1']);
  // const [modalViewDisplay, setModalViewDisplay] = useState<boolean>(false);
  // const [modalDeleteDisplay, setModalDeleteDisplay] = useState<boolean>(false);
  // const [deleteModalMsg, setDeleteModalMsg] = useState<string>("");
  const [m3u8, setM3u8] = useState<string>('https://cph-msl.akamaized.net/hls/live/2000341/test/master.m3u8');
  const [YYYYMMDDStartTime, setYYYYMMDDStartTime] = useState<
    string | undefined
  >(undefined);
  const [startTime, setStartTime] = useState<string | undefined>(undefined);
  // const [sliderData, setSliderData] = useState<any>([]);
  // const [markInfo, setMarkInfo] = useState<any>([]);
  // const [modalType, setModalType] = useState<any>("create");
  // const [markTimeValue, setMarkTimeValue] = useState<any>(undefined);
  // const [modalTimePointId, setModalTimePointId] = useState<any>(undefined);
  // const [markSelect, setMarkSelect] = useState<any>(undefined);
  // const [markTextArea, setMarkTextArea] = useState<any>(undefined);
  // const iconMap = {
  //   edit: "https://dpubstatic.udache.com/static/dpubimg/g7LN7BXD9c/icon_edit.png",
  //   delete:
  //     "https://dpubstatic.udache.com/static/dpubimg/YsDBwfXTSl/icon_delete.png",
  // };
  // const sliderColorImgMap: any = {
  //   // 订单事件
  //   orderEvent: {
  //     color: "rgba(68,125,241,1)",
  //     img: "https://dpubstatic.udache.com/static/dpubimg/tF_qFEt89G/bofang_dingdan.png",
  //   },
  //   // 停留
  //   stayEvent: {
  //     color: "rgba(255,73,73,1)",
  //     img: "https://dpubstatic.udache.com/static/dpubimg/jHbbl9gbkL/bofang_tingliu.png",
  //   },
  //   // 丢失
  //   lostEvent: {
  //     color: "rgba(126,126,153,1)",
  //     img: "https://dpubstatic.udache.com/static/dpubimg/_vghDtQe7X/bofang_xiaoshi.png",
  //   },
  //   // 司机操作
  //   driverEvent: {
  //     color: "rgba(84,191,162,1)",
  //     img: "https://dpubstatic.udache.com/static/dpubimg/verMBu-Ewu/bofang_siji.png",
  //   },
  //   // 平台干预
  //   interposeEvent: {
  //     color: "rgba(245,171,22,1)",
  //     img: "https://dpubstatic.udache.com/static/dpubimg/x6vW8PQ9qm/bofang_ganyu.png",
  //   },
  //   // 乘客操作
  //   passengerEvent: {
  //     color: "rgba(92,219,211,1)",
  //     img: "https://dpubstatic.udache.com/static/dpubimg/YUTysAlx5_/bofang_chengke.png",
  //   },
  //   // 如果以上都没有，用紫色
  //   none: {
  //     color: "rgba(146,84,221,1)",
  //     // todo
  //     img: "https://dpubstatic.udache.com/static/dpubimg/HTJkM1rcBs/bofang_qita.png",
  //   },
  // };

  // const markSelectOptions = [
  //   {
  //     id: 1,
  //     label: "言语骚扰",
  //   },
  //   {
  //     id: 2,
  //     label: "疑似涉性动手",
  //   },
  //   {
  //     id: 3,
  //     label: "醉酒",
  //   },
  //   {
  //     id: 4,
  //     label: "开门声/关门声",
  //   },
  //   {
  //     id: 5,
  //     label: "尖叫声",
  //   },
  //   {
  //     id: 6,
  //     label: "碰撞声",
  //   },
  //   {
  //     id: 7,
  //     label: "呻吟声",
  //   },
  //   {
  //     id: 8,
  //     label: "哭泣声",
  //   },
  //   {
  //     id: 9,
  //     label: "救护车到达",
  //   },
  //   {
  //     id: 10,
  //     label: "关车门声",
  //   },
  //   {
  //     id: 11,
  //     label: "礼貌下车",
  //   },
  //   {
  //     id: 11,
  //     label: "目的地无停留驶离",
  //   },
  // ];

  // const getM3u8AndImages = async () => {
  //   const { data: resData = {} } = await req("streamInfo", {
  //     orderId: `${orderId}`,
  //     district: `${district}`,
  //     productId: +productId,
  //   });
  //   const { errno, data } = resData;
  //   if (errno === 0) {
  //     const { m3u8Url, waveformUrlList = [] } = data;
  //     // 错误数据拦截
  //     if (["", undefined, null].includes(m3u8Url)) {
  //       message.error("音频加载失败！");
  //       return;
  //     }
  //     for (let i = 0; i < waveformUrlList.length; i++) {
  //       if (typeof waveformUrlList[i] !== "string") {
  //         message.error("音频加载失败！");
  //         return;
  //       }
  //     }
  //     setImages(waveformUrlList);
  //     setM3u8('https://cph-msl.akamaized.net/hls/live/2000341/test/master.m3u8');
  //   } else {
  //     if (ajaxM3u8TimesFlag < 10) {
  //       ajaxM3u8TimesFlag++;
  //       setTimeout(async () => {
  //         await getM3u8AndImages();
  //       }, 50);
  //     } else {
  //       if (ajaxM3u8TimesFlag !== 100) {
  //         message.error("音频加载失败");
  //       }
  //     }
  //   }
  // };

  const computedYYYYMMDDToTime = (time: any) => {
    const _time = moment(time, "YYYY-MM-DD HH:mm:ss");
    if (!_time.isValid()) {
      message.error("无效的时间数据！");
      return;
    }
    return (
      _time.get("hour") * 60 * 60 +
      _time.get("minute") * 60 +
      _time.get("second")
    );
  };

  useImperativeHandle(ref, () => {
    return {
      setAudioCurrentTime,
      addAudioEventListener,
      setAudioPlayingStatus,
      setAudioVolume,
    };
  });

  // 获取startTime + 录音信息
  // useEffect(() => {
  //   (async () => {
  //     const { data: resData = {} } = await req("queryVoiceInfo", {
  //       orderId: `${orderId}`,
  //       district: `${district}`,
  //       productId: +productId,
  //     });
  //     const { errno, data } = resData;
  //     if (errno === 0) {
  //       const { fragmentInfo = [], markInfo = [] } = data;
  //       const _startTime = fragmentInfo[0] && fragmentInfo[0].startTime;
  //       if (!moment(_startTime, "YYYY-MM-DD HH:mm:ss").isValid()) {
  //         message.error("无效的时间数据！");
  //         return;
  //       }

  //       setStartTime(computedYYYYMMDDToHHssmm(_startTime));
  //       setYYYYMMDDStartTime(_startTime);
  //       // setMarkInfo(
  //       //   markInfo?.map((item: any) => ({
  //       //     ...item,
  //       //     canEdit: true,
  //       //   })) || []
  //       // );
  //     }
  //   })();
  // }, []);

  // 获得时间轴相关数据
  // useEffect(() => {
  //   (async () => {
  //     const { data: resData = {} } = await req("timeline", {
  //       orderId: `${orderId}`,
  //       district: `${district}`,
  //       productId: +productId,
  //     });
  //     const { errno, data = [] } = resData;
  //     if (errno === 0) {
  //       const arr: any = [];
  //       let flag = true;
  //       data.forEach((item: any, index: number) => {
  //         const { startTime, type, orderStatus } = item;

  //         if (!moment(startTime).isValid()) {
  //           flag = false;
  //           message.error("无效的进度条时间数据！");
  //         } else {
  //           const lastNode = data[index - 1];
  //           const otherBgColor = "rgba(126,126,153,.1)";
  //           const centerBgColor = "rgba(68,125,241,.5)";
  //           const leftNodeBgColor =
  //             lastNode && lastNode.orderStatus === 2
  //               ? centerBgColor
  //               : otherBgColor;
  //           const rightNodeBgColor =
  //             orderStatus === 2 ? centerBgColor : otherBgColor;
  //           arr.push({
  //             ...item,
  //             showTime: computedYYYYMMDDToHHssmm(startTime),
  //             clickTime: computedYYYYMMDDToTime(startTime),
  //             color:
  //               sliderColorImgMap[type]?.color || sliderColorImgMap.none.color,
  //             img: sliderColorImgMap[type]?.img || sliderColorImgMap.none.img,
  //             type: item.type || "none",
  //             leftNodeBgColor,
  //             rightNodeBgColor,
  //           });
  //         }
  //       });
  //       if (flag) {
  //         setSliderData(arr);
  //       }
  //     }
  //   })();
  // }, []);

  // 获得m3u8 + 图片
  // useEffect(() => {
  //   (async () => {
  //     await getM3u8AndImages();
  //   })();
  // }, []);

  // componentWillUnMount
  useEffect(() => {
    return () => {
      ajaxM3u8TimesFlag = 100;
    };
  }, []);

  const setAudioVolume = (volume: number) => {
    if (typeof volume === "number" && volume >= 0 && volume <= 100) {
      cRef?.current?.handleChangeSlider(volume);
    }
  };

  const setAudioPlayingStatus = (status: any) => {
    cRef?.current?.propsSetAudioPlayingStatus(status);
  };

  const handleMouseRightClick = (date: any = {}) => {
    const { fromZero } = date;
    if (
      !moment(YYYYMMDDStartTime, "YYYY-MM-DD HH:mm:ss").isValid() ||
      typeof fromZero !== "number"
    ) {
      message.error("无效的进度条时间数据!");
      return;
    }
    // setModalType("create");
    // setModalViewDisplay(true);
    // setMarkTimeValue(
    //   moment(YYYYMMDDStartTime, "YYYY-MM-DD HH:mm:ss")
    //     .add(moment.duration({ s: fromZero }))
    //     .format("YYYY-MM-DD HH:mm:ss")
    // );
  };

  // const handleEditMarkItem = (id: number, timePoint: string, desc: string) => {
  //   setModalType("edit");
  //   setModalViewDisplay(true);
  //   setMarkTimeValue(timePoint);
  //   setMarkTextArea(desc);
  //   setModalTimePointId(id);
  // };

  // const handleDeleteMarkItem = (
  //   id: number,
  //   timePoint: string,
  //   desc: string
  // ) => {
  //   setModalDeleteDisplay(true);
  //   setModalTimePointId(id);
  //   setDeleteModalMsg(`【${timePoint} -- ${desc}】`);
  // };

  // const handleAfterSubmitData = async () => {
  //   // 不需要更新startTime
  //   const { data: resData = {} } = await req("queryVoiceInfo", {
  //     orderId: `${orderId}`,
  //     district: `${district}`,
  //     productId: +productId,
  //   });
  //   const { errno, data = [] } = resData;
  //   if (errno === 0) {
  //     const { markInfo = [] } = data;
  //     // setMarkInfo(
  //     //   markInfo.map((item: any) => ({
  //     //     ...item,
  //     //     canEdit: true,
  //     //   }))
  //     // );
  //   }
  //   setModalType("create");
  //   setModalViewDisplay(false);
  //   setModalDeleteDisplay(false);
  //   setMarkTimeValue(undefined);
  //   setModalTimePointId(undefined);
  //   setMarkTextArea(undefined);
  // };

  // const handleSubmitModalDate = async () => {
  //   if (
  //     !["", null, undefined].includes(markTextArea) &&
  //     markTextArea.length <= 200
  //   ) {
  //     const { data: resData = {} } = await req("upsertVoiceMarkInfo", {
  //       orderId: `${orderId}`,
  //       productId: +productId,
  //       optType: modalType === "create" ? 1 : 2,
  //       desc: markTextArea,
  //       timePoint: markTimeValue,
  //       id: modalType === "create" ? undefined : +modalTimePointId,
  //     });
  //     const { errno, data = [] } = resData;
  //     if (errno === 0) {
  //       message.success("标记成功！");
  //       await handleAfterSubmitData();
  //     }
  //   } else {
  //     message.error("标记信息不能为空，且不能超过200字！");
  //   }
  // };

  // const handleSubmitModalDateDelete = async () => {
  //   const { data: resData = {} } = await req("deleteVoiceMarkInfo", {
  //     orderId: `${orderId}`,
  //     productId: +productId,
  //     id: +modalTimePointId,
  //   });
  //   const { errno, data = [] } = resData;
  //   if (errno === 0) {
  //     message.success("删除成功！");
  //     await handleAfterSubmitData();
  //   }
  // };

  const setAudioCurrentTime = (time: string, autoPlay: any) => {
    const _time = computedYYYYMMDDToTime(time);
    cRef?.current?.setGameCurrentTime(_time, autoPlay);
  };

  const addAudioEventListener = (type: any, fuc: any) => {
    switch (type) {
      case "audioTimeChange":
        break;
      default:
        message.error("无效的事件！");
        break;
    }
  };

  const onAudioReady = () => {
    onReady(true);
    // if (YYYYMMDDStartTime && Array.isArray(sliderData) && sliderData.length) {
    //   if (!moment(YYYYMMDDStartTime, "YYYY-MM-DD HH:mm:ss").isValid()) {
    //     message.error("无效的音频时间！");
    //     return;
    //   }
    //   const startNumberTime = computedYYYYMMDDToNumber(YYYYMMDDStartTime);
    //   const endNumberTime = computedYYYYMMDDToNumber(
    //     moment(YYYYMMDDStartTime, "YYYY-MM-DD HH:mm:ss")
    //       .add(cRef?.current?.getAudioDuration(), "s")
    //       .format("YYYY-MM-DD HH:mm:ss")
    //   );

    //   // if (startNumberTime && endNumberTime) {
    //   //   setSliderData(
    //   //     sliderData.map((item: any) => {
    //   //       const { startTime } = item;
    //   //       const _time = computedYYYYMMDDToNumber(startTime);

    //   //       if (_time && _time >= startNumberTime && _time <= endNumberTime) {
    //   //         return {
    //   //           ...item,
    //   //           canPlayAudio: true,
    //   //         };
    //   //       } else {
    //   //         return {
    //   //           ...item,
    //   //           canPlayAudio: false,
    //   //         };
    //   //       }
    //   //     })
    //   //   );
    //   // }
    // }
  };

  // const computedYYYYMMDDToNumber = (time: string) => {
  //   const YYYYMMDDTime = moment(time, "YYYY-MM-DD HH:mm:ss");
  //   if (!YYYYMMDDTime.isValid()) {
  //     return;
  //   } else {
  //     return YYYYMMDDTime.format("X");
  //   }
  // };

  // const handleClickRecord = (timePoint: moment.MomentInput, desc: any) => {
  //   if (!moment(timePoint).isValid()) {
  //     message.error("无效的时间数据！");
  //   } else {
  //     if (onClickRecord) {
  //       onClickRecord(desc);
  //     }
  //     cRef?.current?.setGameCurrentTime(
  //       computedYYYYMMDDToTime(timePoint),
  //       true
  //     );
  //   }
  // };

  // const sliderWrapperWidth = sliderWrapperRef?.current?.clientWidth;

  return (
    <div className={"superAudio"}>
      <div
        className={"superAudio-left"}
        style={{
          width: `calc(100% - ${markListWidth || "270px"} - 20px)`,
        }}
      >
        <div className={"superAudio-left-sliderWrap"} ref={sliderWrapperRef}>
          {/* {sliderData.length ? (
            <div className={"superAudio-left-slider"}>
              {sliderData.map((item: any, index: number) => {
                const {
                  desc,
                  name,
                  color,
                  showTime,
                  clickTime,
                  type,
                  canPlayAudio,
                  img,
                  leftNodeBgColor,
                  rightNodeBgColor,
                } = item;
                return (
                  <ToolTip
                    key={index}
                    contentText={
                      <div
                        className={"superAudio-left-slider-item"}
                        onClick={() => {
                          const time = cRef?.current?.setGameCurrentTime(
                            clickTime,
                            true
                          );
                          onAudioTimeLineClick(
                            time
                              ? { ...time, play: true, name }
                              : { play: false, name }
                          );
                        }}
                      >
                        <div className={"superAudio-left-slider-item-line"}>
                          <div
                            className={"superAudio-left-slider-item-line-item"}
                            style={{
                              backgroundColor: leftNodeBgColor,
                            }}
                          />
                          <div
                            className={"superAudio-left-slider-item-line-item"}
                            style={{
                              backgroundColor: rightNodeBgColor,
                            }}
                          />
                        </div>
                        <div className={"superAudio-left-slider-item-time"}>
                          {showTime}
                        </div>
                        <div className={"superAudio-left-slider-item-dot"}>
                          <div
                            className={`superAudio-left-slider-item-dot-center superAudio-left-slider-item-dot-center-${type}`}
                            style={
                              canPlayAudio
                                ? {
                                    background: "no-repeat center center",
                                    backgroundSize: "cover",
                                    backgroundImage: `url("${img}")`,
                                  }
                                : {
                                    backgroundColor: `${color}`,
                                  }
                            }
                          />
                        </div>
                        <div
                          className={"superAudio-left-slider-item-msg"}
                          style={
                            ["开始计费", "结束计费"].includes(name)
                              ? {
                                  color: "#447DF1",
                                }
                              : {}
                          }
                        >
                          {name.length <= 6
                            ? name
                            : name.slice(0, 6 - 2) + ".."}
                        </div>
                      </div>
                    }
                    text={`${desc}`}
                    style={
                      sliderData?.length * 90 >= sliderWrapperWidth
                        ? {}
                        : {
                            width: "100%",
                          }
                    }
                  />
                );
              })}
            </div>
          ) : (
            "暂无数据"
          )} */}
        </div>
        <div className={"superAudio-left-canvas"}>
          <Canvas
            handleMouseRightClick={handleMouseRightClick}
            cRef={cRef}
            startTime={startTime}
            YYYYMMDDStartTime={YYYYMMDDStartTime}
            canvasPlayingFuc={onAudioPlaying ?? (() => {})}
            canvasJumpFuc={onAudioJump ?? (() => {})}
            onAudioPlayOrPause={onAudioPlayOrPause ?? (() => {})}
            onAudioPlaybackRateChange={onAudioPlaybackRateChange ?? (() => {})}
            onAudioVolumeChange={onAudioVolumeChange ?? (() => {})}
            onAudioJumpButtonClick={onAudioJumpButtonClick ?? (() => {})}
            onAudioReady={onAudioReady}
            onClickPlayBtn={onClickPlayBtn ?? (() => {})}
            images={images}
            m3u8={m3u8}
          />
        </div>
      </div>
      {/* <div
        className={"superAudio-right"}
        style={
          markListWidth
            ? {
                width: markListWidth,
              }
            : {}
        }
      >
        <div className={"superAudio-right-title"}>{"录音记录"}</div>
        <div className={"superAudio-right-list"}>
          <ul className={"superAudio-right-list-ul"}>
            {markInfo.length
              ? markInfo?.map((item: any, index: number) => {
                  const { id, timePoint, desc, canEdit, user, dept } = item;
                  return (
                    <li
                      className={"superAudio-right-list-ul-li"}
                      key={index}
                      onClick={() => handleClickRecord(timePoint, desc)}
                    >
                      <div className={"superAudio-right-list-ul-li-right"}>
                        <div
                          className={"superAudio-right-list-ul-li-right-top"}
                        >
                          <div
                            className={
                              "superAudio-right-list-ul-li-right-top-time"
                            }
                          >
                            {timePoint}
                          </div>
                          {canEdit ? (
                            <div
                              className={
                                "superAudio-right-list-ul-li-right-top-icon"
                              }
                              style={{
                                backgroundImage: `url("${iconMap.edit}")`,
                              }}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleEditMarkItem(id, timePoint, desc);
                              }}
                            />
                          ) : null}
                          {canEdit ? (
                            <div
                              className={
                                "superAudio-right-list-ul-li-right-top-icon"
                              }
                              style={{
                                backgroundImage: `url("${iconMap.delete}")`,
                              }}
                              onClick={(e) => {
                                e.stopPropagation();
                                handleDeleteMarkItem(id, timePoint, desc);
                              }}
                            />
                          ) : null}
                        </div>
                        {![null, undefined, ""].includes(user) ? (
                          <div
                            className={"superAudio-right-list-ul-li-right-top"}
                          >
                            <div
                              className={
                                "superAudio-right-list-ul-li-right-top-time"
                              }
                            >
                              编辑者：{user || "AI"}【{dept ?? "--"}】
                            </div>
                          </div>
                        ) : null}
                        <div
                          className={"superAudio-right-list-ul-li-right-msg"}
                        >
                          {desc}
                        </div>
                      </div>
                    </li>
                  );
                })
              : "暂无数据"}
          </ul>
        </div>
      </div> */}
      {/* <Modal
        title={"人工标记"}
        visible={modalViewDisplay}
        onCancel={() => setModalViewDisplay(false)}
        onOk={handleSubmitModalDate}
        maskClosable={false}
        destroyOnClose={false}
      >
        <FormItem
          title={"时间"}
          type={"input"}
          disabled={true}
          allowClear={false}
          value={markTimeValue}
        />
        <FormItem
          title={"标记类型"}
          type={"select"}
          options={markSelectOptions}
          onChange={(e: any) => {
            setMarkSelect(e);
            const value =
              markSelectOptions.find((item) => `${item.id}` === `${e}`)
                ?.label || "";
            e && setMarkTextArea((markTextArea || "") + value);
          }}
          value={markSelect}
        />
        <FormItem
          title={"风险标记"}
          type={"textArea"}
          onChange={(ev: any) => {
            ev.persist();
            setMarkTextArea(ev.target.value);
          }}
          value={markTextArea}
        />
      </Modal> */}
      {/* <Modal
        title={"删除人工标记"}
        visible={modalDeleteDisplay}
        onCancel={() => setModalDeleteDisplay(false)}
        onOk={handleSubmitModalDateDelete}
        maskClosable={false}
        destroyOnClose={false}
      >
        <div>您确定要删除{deleteModalMsg}吗？</div>
      </Modal> */}
    </div>
  );
};

export default XBaseFn;
